import { defaultEnum, selectList, upLoadList } from "./enums";
import useStore from "../stores/index";
export const getTimeFormat = (
  time: string | Date,
  format = "YYYY.MM.DD"
): string => {
  const t =
    typeof time === "string"
      ? new Date(time.replace(/-/g, "/"))
      : new Date(time);
  const year = t.getFullYear();
  const month = t.getMonth() + 1;
  const day = t.getDate();
  const hour = t.getHours();
  const minute = t.getMinutes();
  const second = t.getSeconds();

  return format
    .replace("YYYY", year.toString())
    .replace("MM", month.toString().padStart(2, "0"))
    .replace("DD", day.toString().padStart(2, "0"))
    .replace("HH", hour.toString().padStart(2, "0"))
    .replace("mm", minute.toString().padStart(2, "0"))
    .replace("ss", second.toString().padStart(2, "0"));
};
export const timeStr = (data: string | number): string => {
  return data.toString().padStart(2, "0");
};

export const formatDate = (date: any, format = "YYYY-MM-DD") => {
  return getTimeFormat(date, format);
};

//跳转小程序
export const toXcx = (url: string, path = "", type = 0) => {
  // #ifdef  APP-PLUS
  plus.share.getServices((resList) => {
    const sweixin = resList.find((item) => item.id === "weixin");
    if (sweixin) {
      sweixin.launchMiniProgram({
        id: url,
        path,
        type,
      });
    }
  });
  // #endif
  // #ifdef  MP-WEIXIN
  uni.navigateToMiniProgram({
    appId: url,
    path,
    success: (res) => {},
    fail: (err) => {
      console.log(err, "eeee");
    },
  });
  // #endif
};

export const getAppQX = () => {};

// 倒计时
export const timerOut = (timer: number): string => {
  const hour = Math.floor((timer / 3600) % 24).toString();
  const minute = Math.floor((timer / 60) % 60).toString();
  const second = Math.floor(timer % 60).toString();
  return (
    hour.padStart(2, "0") +
    ":" +
    minute.padStart(2, "0") +
    ":" +
    second.padStart(2, "0")
  );
};

// 手机号加密
export const mobileEncryption = (mobile: string): string => {
  return mobile.replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3");
};

// 银行卡加密
export const bankEncryption = (bank: string): string => {
  if (bank.length <= 7) {
    return bank; // 如果银行卡号长度不足，直接返回原值
  }
  return bank.slice(0, 3) + "*****" + bank.slice(-4);
};

// 支付
export const pay = (provider: "alipay" | "wxpay", orderInfo: string | any) => {
  console.log(orderInfo, "orderInfoorderInfo");
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    uni.requestPayment({
      provider,
      orderInfo,
      success: (res: any) => {
        resolve(res);
      },
      fail: (err: any) => {
        console.log(err, "errr");
        reject(err);
      },
    });
    // #endif

    // #ifdef MP-WEIXIN
    wx.requestPayment({
      timeStamp: String(orderInfo.timeStamp),
      nonceStr: orderInfo.nonceStr,
      package: orderInfo.package,
      signType: orderInfo.signType,
      paySign: orderInfo.paySign,
      success: (res: any) => {
        resolve(res);
      },
      fail: (err: any) => {
        console.log(err, "errerr");
        reject(err);
      },
    });
    // #endif
  });
};

// 字符串添加

export const insertStr = (
  soure: string,
  start: number,
  newStr: string
): string => {
  return soure.slice(0, start) + newStr + soure.slice(start);
};

// 当月多少天
export const getCountDays = (date: string | number, time?: number): number => {
  const year = time || new Date().getFullYear();
  if (Number(date) === 2) {
    return year % 4 === 0 ? 29 : 28;
  }
  const dDate = ["1", "3", "5", "7", "8", "10", "12"];
  return dDate.includes(date.toString()) ? 31 : 30;
};

// 保留小数点
export const fixed = (num: number, fle: number): number => {
  return Number(num.toFixed(fle));
};

// 保存图片
export const saveImg = (url: string) => {
  // #ifdef APP-PLUS
  uni.saveImageToPhotosAlbum({
    filePath: url,
    success: () => {
      showTost("保存成功！");
    },
    fail: () => {
      showTost("保存失败！");
    },
  });
  // #endif
  // #ifdef H5
  // 处理跨域图片
  const saveImageToPC = (imgUrl: string) => {
    // 创建一个新的Image对象
    const image = new Image();
    // 解决跨域问题
    image.setAttribute("crossOrigin", "anonymous");
    image.src = imgUrl;

    // 图片加载完成后处理
    image.onload = () => {
      // 创建canvas
      const canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;

      // 将图片画到canvas上
      const ctx = canvas.getContext("2d");
      if (ctx) {
        ctx.drawImage(image, 0, 0, image.width, image.height);

        // 将canvas转为base64图片数据
        const dataURL = canvas.toDataURL("image/png");

        // 创建下载链接
        const a = document.createElement("a");
        a.href = dataURL;
        a.download = "image_" + new Date().getTime() + ".png";
        a.style.display = "none";
        document.body.appendChild(a);

        // 触发下载
        a.click();

        // 移除临时元素
        document.body.removeChild(a);
        showTost("保存成功！");
      } else {
        showTost("保存失败！");
      }
    };

    image.onerror = () => {
      showTost("图片加载失败！");
    };
  };

  // 调用函数
  saveImageToPC(url);
  // #endif
};

// 打电话

export const telephone = (phoneNumber: string) => {
  uni.makePhoneCall({
    phoneNumber,
    success: (res) => {},
    fail: (err) => {
      uni.showToast({
        icon: "none",
        title: "拨打电话失败",
      });
      console.log(err, "errerrerr");
    },
  });
};

// 复制文本
export const copyStr = (text: string) => {
  console.log(text);
  uni.setClipboardData({
    data: text,
    success: () => {
      console.log("text");
    },
  });
};

// toast

export const showTost = (title: string, fn?: Function, t = 600) => {
  uni.showToast({
    icon: "none",
    title,
    duration: 2000,
    success: () => {
      setTimeout(() => {
        fn && fn();
      }, t);
    },
  });
};

// 表单校验

export const checkForm = (
  obj: object,
  NoCheck: Array<string> = [],
  rules?: { [key: string]: { reg?: RegExp; message?: string } },
  noSpan = false,
  toast = true
) => {
  let keys = "";
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (
        (typeof obj[key] === "number" ? !String(obj[key]) : !obj[key]) &&
        !NoCheck.includes(key)
      ) {
        toast &&
          showTost(
            (upLoadList.includes(key)
              ? "请上传"
              : selectList.includes(key)
              ? "请选择"
              : "请填写") + defaultEnum[key]
          );
        keys = key;
        break;
      }
      if (
        (typeof obj[key] === "string" || typeof obj[key] === "number") &&
        /\s/.test(obj[key]) &&
        !noSpan &&
        !NoCheck.includes(key)
      ) {
        keys = key;
        showTost(defaultEnum[key] + "不能包含有空格字符");
        break;
      }

      if (
        !NoCheck.includes(key) &&
        rules?.[key] &&
        !rules[key].reg.test(obj[key])
      ) {
        keys = key;
        toast && showTost(rules[key]?.message || "");
        break;
      }

      if (
        Array.isArray(obj[key]) &&
        !obj[key].length &&
        !NoCheck.includes(key)
      ) {
        toast &&
          showTost(
            (upLoadList.includes(key)
              ? "请上传"
              : selectList.includes(key)
              ? "请选择"
              : "请填写") + defaultEnum[key]
          );
        keys = key;
        break;
      }
    }
  }
  return keys;
};

interface Rules {
  [key: string]:
    | { reg?: RegExp; message?: string; require?: boolean }
    | Array<{ reg?: RegExp; message?: string; require?: boolean }>;
}

export const checkFormData = (formData: Form, rules?: Rules) => {
  return new Promise((resolve, reject) => {
    for (let key in formData) {
      if (formData.hasOwnProperty(key)) {
        // !formData[key] && reject(key);
        // Array.isArray(formData[key]) && !formData[key].length && reject(key);
        // !Object.keys(formData[key])?.length && reject(key);
        if (rules?.[key]) {
          const rule = rules?.[key];
          if (Array.isArray(rule)) {
            for (let i = 0; i < rule.length; i++) {
              if (!checkRule(rule[i], formData[key])) {
                reject(key);
                break;
              }
            }
          } else {
            !checkRule(rule, formData[key]) && reject(key);
          }
        }
      }
    }
    resolve(true);
  });
};

const checkRule = (
  rule: { reg?: RegExp; message?: string; require?: boolean },
  value: any
) => {
  const reg = new RegExp(rule.reg as any);
  if (rule.require && !value) {
    uni.showToast({
      title: rule.message || "",
      icon: "none",
    });
    return false;
  }
  if (!reg.test(value)) {
    uni.showToast({
      title: rule.message,
      icon: "none",
    });
    return false;
  } else {
    return true;
  }
};

interface Form {
  [key: string]: any;
}

// 清除表单
export const clearForm = (data: Form): Form => {
  for (let key in data) {
    if (data.hasOwnProperty(key)) {
      if (typeof data[key] === "boolean") {
        data[key] = false;
      }
      if (Array.isArray(data[key])) {
        data[key] = [];
      } else if (typeof data[key] === "object") {
        data[key] = {};
      }
      if (typeof data[key] === "number") {
        data[key] = 0;
      }
      if (typeof data[key] === "string") {
        data[key] = "";
      }
    }
  }
  return data;
};
// 缓存
export const setStorage = (key: string, data: any) => {
  uni.setStorageSync(key, JSON.stringify(data));
};

export const getStorage = (key: string) => {
  try {
    return JSON.parse(uni.getStorageSync(key));
  } catch (err) {
    return null;
  }
};

// 清除缓存
export const clearStorage = (key?: string) => {
  try {
    key ? uni.removeStorageSync(key) : uni.clearStorageSync();
  } catch (e) {
    // error
  }
};

// 转换
export const priceFormat = (price: number) => {
  return (Number(price) < 0 ? "-" : "") + "￥" + +Math.abs(price);
};

export const getSystemInfoSync = () => {
  return uni.getSystemInfoSync();
};
// 获取当前屏幕高度
export const getWindowHeight = () => {
  const { screenHeight, statusBarHeight, windowHeight, osName, deviceModel } =
    uni.getSystemInfoSync();

  const notPhone = [
    "iPhone 5",
    "iPhone 6",
    "iPhone 7",
    "iPhone 8",
    "iPhone 6 Plus",
    "iPhone 7 Plus",
    "iPhone 8 Plus",
  ];

  let iosBottom = 0;
  if (osName === "ios") {
    iosBottom = notPhone.includes(deviceModel) ? 0 : 22;
  }
  // #ifdef  APP-PLUS
  return isNaN(screenHeight - statusBarHeight)
    ? screenHeight - iosBottom
    : screenHeight - statusBarHeight - iosBottom;
  // #endif

  // #ifdef  MP-WEIXIN
  const { width } = wx.getMenuButtonBoundingClientRect();
  return isNaN(screenHeight - statusBarHeight - width)
    ? screenHeight - iosBottom
    : screenHeight - statusBarHeight - width - iosBottom;
  // #endif
};

// 跳转
export const navTo = (
  url: string,
  type: "navigateTo" | "reLaunch" | "redirectTo" | "switchTab" | "navigateBack",
  login?: string | boolean
) => {
  if (login) {
    if (getStorage("token") && getStorage("userId")) {
      switch (type) {
        case "navigateTo":
          uni.navigateTo({
            url,
          });
          break;
        case "reLaunch":
          uni.reLaunch({
            url,
          });
          break;
        case "redirectTo":
          uni.redirectTo({
            url,
          });
          break;
        case "switchTab":
          uni.switchTab({
            url,
          });
          break;
        case "navigateBack":
          uni.navigateBack({
            delta: 1,
          });
          break;
      }

      // uni[type]({
      //   url,
      // });
    } else {
      uni.showToast({
        icon: "none",
        title: "未登录，请登录",
        success: () => {
          setTimeout(() => {}, 300);
        },
      });
    }
    return;
  }
  uni[type]({
    url,
  });
};

export const checkLogin = () => {
  return new Promise((resolve, reject) => {
    if (!getStorage("token") || !getStorage("userId")) {
      const userList = getStorage("userList");

      if (userList?.length) {
        const store = useStore();
        store.setIsLoginModal(true);
      } else {
        uni.navigateTo({
          url: "/pages/views/login",
        });
      }

      // const store = useStore();
      // const userList = getStorage("userList");
      // if (userList?.length) {
      //   const showUserList = [
      //     ...userList?.map((i: any) => `${i.nickName}-(${i.mobile})`),
      //     "选择其他账号",
      //   ];
      //   uni.showActionSheet({
      //     title: "请选择登录用户",
      //     itemList: showUserList,
      //     // cancel: '选择其他账号登录',
      //     success: async (res) => {
      //       const index = res.tapIndex as number;
      //       if (index === showUserList.length - 1) {
      //         uni.navigateTo({
      //           url: "/pages/views/login",
      //         });
      //         return;
      //       }
      //       setStorage("token", userList[index].token);
      //       setStorage("userId", userList[index].userId);
      //       await store.setUserInfo();
      //     },
      //     fail: () => {
      //       console.log("failfailfail");
      //     },
      //   });
      // } else {
      //   uni.navigateTo({
      //     url: "/pages/views/login",
      //   });
      // }
      return reject(false);
    }
    return resolve(true);
  });
};

export const userLevelType = {
  "0": "普通用户",
  "1": "一级经销商 ",
  "2": "二级经销商",
  "3": "三级经销商",
  "4": "四级经销商",
  "5": "五级经销商",
  "6": "共享大使",
};

export const bussinessPriceType = [
  {
    value: 0,
    label: "佣金金额",
  },
  {
    value: 1,
    label: "充电收益",
  },
  {
    value: 2,
    label: "经销商销售收益",
  },
  {
    value: 7,
    label: "渠道收益",
  },
];

export const withdrawalType = [
  {
    value: 0,
    label: "佣金金额",
  },
  {
    value: 1,
    label: "充电收益",
  },
  {
    value: 2,
    label: "经销商销售收益",
  },
  {
    value: 3,
    label: "渠道收益",
  },
]

export const exchangeTypeEnum = {
  0: "amount",
  1: "chargingAmount",
  2: "merchantAmount",
  7: "channelAmount",
  3: "channelAmount",
};

export default {
  setStorage,
  getStorage,
  clearStorage,
  navTo,
};
